<template>

	<!--顶部新增、查询-->
    <div style="margin-bottom: 10px;">
        <el-button type="primary" style="margin-right: 10px;" @click= "AddMerchandiseClick">新增商品</el-button>
        <el-input v-model="MerchandiseSearchInput" style="width: 240px" placeholder="按商品编号搜索" :prefix-icon="Search"/>
    </div>

    <!--商品数据展示表格-->
    <el-table :data="GetMerchandiseData" style="width: 100%; margin-top: 15px;" highlight-current-row>
        <el-table-column fixed prop="merchandiseId" label="商品编号" align="center"/>
        <el-table-column prop="merchandiseName" label="商品名称" align="center"/>
        <el-table-column prop="merchandiseCategoryName" label="商品类别" align="center"/>
        <el-table-column prop="merchandisePrice" label="销售单价" align="center"/>
        <el-table-column prop="merchandiseState" label="销售状态" align="center"/>
        <el-table-column prop="merchandiseCategoryId" label="商品类型编号" align="center"/>
        <el-table-column prop="merchandiseGoodsId" label="商品货物编号" align="center"/>
        <el-table-column fixed="right" label="商品操作" min-width="120" align="center">
            <template #default="ThisRowData">
                <el-button size="small" type="primary" @click="EditMerchandiseClick(ThisRowData.row)"style="margin-right: 5px;">
                    <el-icon><Edit /></el-icon>
                    修改
                </el-button>
                <el-button size="small" type="danger" @click="DeleteMerchandiseClick(ThisRowData.row)":disabled="ThisRowData.row.productCount > 0"tooltip-content="分类下有商品，不可删除">
                    <el-icon><Delete /></el-icon>
                    删除
                </el-button>
            </template>
        </el-table-column>

        <template #empty>
            <el-empty description="暂无商品数据" />
        </template>
    </el-table>

    <!-- 删除的对话框 -->
    <el-dialog v-model="DeleteMerchandiseDialog" title="商品删除提示" width="500">
        <span>是否确定删除该商品？</span><br>
        <span>商品编号: {{ RowMerchandiseData.merchandiseId }}</span><br>
        <span>商品名称: {{ RowMerchandiseData.merchandiseName }}</span><br>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="DeleteMerchandiseDialog = false">
                    取消
                </el-button>
                <el-button type="primary" @click="removeMerchandise">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 修改的对话框 -->
    <el-dialog v-model="EditMerchandiseDialog" title="商品信息修改" width="500">
        <el-form :model="PutMerchandiseData">
            <el-form-item label="商品名称">
                <el-input v-model="PutMerchandiseData.merchandiseName" />
            </el-form-item>
            <el-form-item label="商品类型">
                <el-select v-model="PutMerchandiseData.merchandiseCategoryId" placeholder="请选择商品类型">
                    <el-option v-for="item in CategoryNameOptions" :key="item.categoryId" :label="item.categoryName"
                        :value="item.categoryId" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品价格">
                <el-input-number v-model="PutMerchandiseData.merchandisePrice" :precision="2" :step="0.1" :max="10">
                    <template #suffix><span>￥</span></template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="销售状态">
                <el-select v-model="PutMerchandiseData.merchandiseState" placeholder="请选择商品销售类型">
                    <el-option label="在售" value="在售" />
                    <el-option label="售罄" value="售罄" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="EditMerchandiseDialog = false">
                    取消
                </el-button>
                <el-button type="primary" @click="PutMerchandise">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 新增的对话框 -->
    <el-dialog v-model="AddMerchandiseDialog" title="添加商品" width="500">
        <el-form :model="PostMerchandiseData">
            <el-form-item label="货品名称">
                <el-select v-model="PostMerchandiseData.merchandiseGoodsId" filterable placeholder="搜索货品名称">
                    <el-option v-for="item in GoodsOptions" :key="item.goodsId" :label="item.goodsName"
                        :value="item.goodsId" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品名称">
                <el-input v-model="PostMerchandiseData.merchandiseName" />
            </el-form-item>
            <el-form-item label="商品类型">
                <el-select v-model="PostMerchandiseData.merchandiseCategoryId" placeholder="请选择商品类型">
                    <el-option v-for="item in CategoryNameOptions" :key="item.categoryId" :label="item.categoryName"
                        :value="item.categoryId" />
                </el-select>
            </el-form-item>
            <el-form-item label="商品价格">
                <el-input-number v-model="PostMerchandiseData.merchandisePrice" :precision="2" :step="0.1" :max="10">
                    <template #suffix><span>￥</span></template>
                </el-input-number>
            </el-form-item>
            <el-form-item label="销售状态">
                <el-select v-model="PostMerchandiseData.merchandiseState" placeholder="请选择商品销售类型">
                    <el-option label="在售" value="在售" />
                    <el-option label="售罄" value="售罄" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="AddMerchandiseDialog = false">
                    取消
                </el-button>
                <el-button type="primary" @click="PostMerchandise">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang='ts' setup name='Merchandise'>

// 导入必要组件
import axios from 'axios';
import { reactive, ref, onMounted, watch } from 'vue';
import { ElNotification } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 对话框显示参数
let AddMerchandiseDialog = ref(false)
let EditMerchandiseDialog = ref(false)
let DeleteMerchandiseDialog = ref(false)

// 表格单行商品数据
let RowMerchandiseData = reactive({
    merchandiseId: 0,
    merchandiseName: '',
    merchandiseCategoryName: '',
    merchandisePrice: 0,
    merchandiseState: '',
    merchandiseCategoryId: 0,
    merchandiseGoodsId: 0
})

// 生命周期钩子，组件挂载后初始化数据
onMounted(async () => {
    await GetCategory()
    await GetWarehouse()
    await GetMerchandise()
})

// 根据分类ID获取分类名称
const getCategoryName = (categoryId: number) => {
    if (!CategoryNameOptions.value) return '未知分类';
    const category = CategoryNameOptions.value.find(item => item.categoryId === categoryId);
    return category ? category.categoryName : '未知分类';
};

// 添加商品回调
function AddMerchandiseClick() {

    // 重置NewData为初始状态
    PostMerchandiseData = reactive({
        merchandiseId: 0,
        merchandiseName: '',
        merchandiseCategoryName: '',
        merchandisePrice: 0,
        merchandiseState: '',
        merchandiseCategoryId: null,
        merchandiseGoodsId: null
    });

    // 打开对话框
    AddMerchandiseDialog.value = true;
}

// 删除商品回调
function DeleteMerchandiseClick(RowData: any) {

    // 打开对话框
    DeleteMerchandiseDialog.value = true

    // 保存行数据
    RowMerchandiseData = RowData

    // 调试输出
    console.log(RowMerchandiseData)
}

// 修改商品回调
async function EditMerchandiseClick(RowData: any) {
    try {
        // 根据商品ID获取商品详情
        console.log("nihao")
        console.log(RowData)
        const response = await axios.get(`/api/merchandise/${RowData.merchandiseId}`)
        console.log('获取商品详情成功:', response.data)
        PutMerchandiseData = reactive({ ...response.data.data });
        EditMerchandiseDialog.value = true
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '获取商品信息失败: ' + error,
            type: 'error',
        })
        console.error('获取商品详情失败:', error)
    }
}

// GET ------------------------------------------ GET //

// GET: 存放获取的商品数据
const GetMerchandiseData = ref([])

// GET: 存放获取的分类数据
const CategoryNameOptions = ref<{ categoryId: number; categoryName: string }[]>([]);

// GET: 存放获取的货品数据
const GoodsOptions = ref<{ goodsId: number; goodsName: string }[]>([])

// GET: 获取商品列表
async function GetMerchandise() {
    try {
        const response = await axios.get("/api/merchandise")
        console.log('获取商品列表成功:', response.data)
        GetMerchandiseData.value = response.data.data || []
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '请求商品列表失败: ' + error,
            type: 'error',
        })
        console.error('获取商品列表失败:', error)
    }
}

// GET: 获取商品分类数据
async function GetCategory() {
    try {
        const response = await axios.get("/api/category");
        console.log("分类数据获取结果：", response.data);
        CategoryNameOptions.value = response.data.data || [];
    } catch (error) {
        ElNotification({ title: "错误", message: "获取商品分类失败: " + error, type: "error" });
        console.error('获取商品分类失败:', error)
    }
}

// GET: 获取仓库货品数据
async function GetWarehouse() {
    try {
        const response = await axios.get("/api/warehouse")
        console.log("货品数据获取结果：", response.data);
        GoodsOptions.value = response.data.data || []
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '获取货品数据失败: ' + error,
            type: 'error',
        })
        console.error('获取货品数据失败:', error)
    }
}

// 输入框接收到的商品编号
let MerchandiseSearchInput = ref('')

// 随时查询
watch(
	MerchandiseSearchInput, (New, Old) => {
		GetMerchandiseById()
	}
)

// GET: 发送请求获得当前搜索商品的数据
async function GetMerchandiseById(){
	try{
		let MerchandiseData = await axios.get(`/api/merchandise/${MerchandiseSearchInput}`)
		GetMerchandiseData.value = MerchandiseData.data.data
	} catch(error){
		ElNotification({
			title: '错误',
			message: '单个商品数据请求失败\n'+error,
			type: 'error',
		})
	}
}

// POST ------------------------------------------ POST //

// POST: 新增的商品数据
let PostMerchandiseData = reactive({
    merchandiseId: 0,
    merchandiseName: '',
    merchandiseCategoryName: '',
    merchandisePrice: 0,
    merchandiseState: '',
    merchandiseCategoryId: null,
    merchandiseGoodsId: null
});

// POST: 新增商品数据
async function PostMerchandise() {

    // 检查必填字段
    if (!PostMerchandiseData.merchandiseName) {
        ElNotification({
            title: '错误',
            message: '商品名称不能为空',
            type: 'error',
        });
        return;
    }

    if (!PostMerchandiseData.merchandiseCategoryId) {
        ElNotification({
            title: '错误',
            message: '请选择商品类型',
            type: 'error',
        });
        return;
    }

    if (PostMerchandiseData.merchandisePrice === null || PostMerchandiseData.merchandisePrice === undefined || PostMerchandiseData.merchandisePrice <= 0) {
        ElNotification({
            title: '错误',
            message: '请设置有效的商品价格',
            type: 'error',
        });
        return;
    }

    // 关闭规画框
    AddMerchandiseDialog.value = false

    // 获取分类名称
    PostMerchandiseData.merchandiseCategoryName = getCategoryName(PostMerchandiseData.merchandiseCategoryId)

    // 调试输出
    console.log('新增商品数据:', PostMerchandiseData)

    // 发送请求
    try {
        const response = await axios.post(
            "/api/merchandise",
            {
                merchandiseName: PostMerchandiseData.merchandiseName,
                merchandiseCategoryId: PostMerchandiseData.merchandiseCategoryId,
                merchandisePrice: PostMerchandiseData.merchandisePrice,
                merchandiseState: PostMerchandiseData.merchandiseState,
                merchandiseGoodsId: PostMerchandiseData.merchandiseGoodsId
            }
        )
        ElNotification({
            title: '成功',
            message: '添加商品成功',
            type: 'success',
        })
        await GetMerchandise()
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '新增失败: ' + error,
            type: 'error',
        })
        console.error('新增商品失败:', error)
    }

    GetMerchandise()
}

// PUT ------------------------------------------ PUT //

// PUT: 修改的商品数据
let PutMerchandiseData = reactive({
    merchandiseId: 0,
    merchandiseName: '',
    merchandiseCategoryName: '',
    merchandisePrice: 0,
    merchandiseState: '',
    merchandiseCategoryId: 0,
    merchandiseGoodsId: 0
})

// PUT: 修改商品数据
async function PutMerchandise() {

    // 验证必填字段
    if (!PutMerchandiseData.merchandiseName) {
        ElNotification({
            title: '错误',
            message: '商品名称不能为空',
            type: 'error',
        });
        return;
    }

    if (!PutMerchandiseData.merchandiseCategoryId) {
        ElNotification({
            title: '错误',
            message: '请选择商品类型',
            type: 'error',
        });
        return;
    }

    if (PutMerchandiseData.merchandisePrice === null || PutMerchandiseData.merchandisePrice === undefined || PutMerchandiseData.merchandisePrice <= 0) {
        ElNotification({
            title: '错误',
            message: '请设置有效的商品价格',
            type: 'error',
        });
        return;
    }
    
    // 关闭对话框
    EditMerchandiseDialog.value = false

    // 获取分类名称
    PutMerchandiseData.merchandiseCategoryName = getCategoryName(PutMerchandiseData.merchandiseCategoryId)

    // 调试输出
    console.log('修改商品数据:', PutMerchandiseData)

    // 发送请求
    try {
        const response = await axios.put(
            `/api/merchandise/${PutMerchandiseData.merchandiseId}`, // 修正此处 URL 携带商品 ID
            {
                merchandiseId: PutMerchandiseData.merchandiseId,
                merchandiseName: PutMerchandiseData.merchandiseName,
                merchandiseCategoryId: PutMerchandiseData.merchandiseCategoryId,
                merchandisePrice: PutMerchandiseData.merchandisePrice,
                merchandiseState: PutMerchandiseData.merchandiseState
            }
        )
        ElNotification({
            title: '成功',
            message: '修改商品信息成功',
            type: 'success',
        })
        await GetMerchandise()
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '修改失败: ' + error,
            type: 'error',
        })
        console.error('修改商品失败:', error)
    }

    GetMerchandise()
}

// DELETE ------------------------------------------ DELETE //

// DELETE: 删除商品数据
async function removeMerchandise() {

    // 关闭对话框
    DeleteMerchandiseDialog.value = false
    
    // 调试输出
    console.log('删除商品ID:', RowMerchandiseData.merchandiseId)

    // 发送请求
    try {
        await axios.delete(`/api/merchandise/${RowMerchandiseData.merchandiseId}`)
        ElNotification({
            title: '成功',
            message: '删除商品成功',
            type: 'success',
        })
        await GetMerchandise()
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '删除失败: ' + error,
            type: 'error',
        })
        console.error('删除商品失败:', error)
    }

    GetMerchandise()
}

</script>

<style scoped>

/* 表格居中设置 */
.el-table-column {
    text-align: center;
}

</style>